#!/usr/bin/env python3
"""
为现有图标添加macOS标准的圆角效果
"""

from PIL import Image, ImageDraw
import os

def create_squircle_mask(size, corner_radius_ratio=0.2237):
    """创建Apple标准的超椭圆(Squircle)蒙版
    corner_radius_ratio = 0.2237 是Apple官方的圆角比例"""
    mask = Image.new('L', (size, size), 0)
    draw = ImageDraw.Draw(mask)

    # Apple的超椭圆使用特殊的数学曲线
    # 这里用多层圆角矩形近似实现超椭圆效果
    radius = int(size * corner_radius_ratio)

    # 绘制基础圆角矩形
    draw.rounded_rectangle([0, 0, size-1, size-1], radius=radius, fill=255)

    # 添加多层细微调整来模拟超椭圆的平滑过渡
    for i in range(10):
        factor = 1.0 - (i * 0.01)  # 逐渐缩小
        current_radius = int(radius * factor)
        offset = i // 2

        coords = [offset, offset, size - offset - 1, size - offset - 1]
        draw.rounded_rectangle(coords, radius=current_radius, fill=255)

    return mask

def apply_rounded_corners_to_icon(input_path, output_path):
    """为图标添加圆角效果"""
    if not os.path.exists(input_path):
        print(f"❌ 错误：找不到输入文件 {input_path}")
        return False

    # 打开原始图标
    original_icon = Image.open(input_path).convert('RGBA')
    size = original_icon.size[0]  # 假设是正方形

    # 创建超椭圆蒙版
    mask = create_squircle_mask(size)

    # 应用蒙版
    rounded_icon = Image.new('RGBA', (size, size), (0, 0, 0, 0))
    rounded_icon.paste(original_icon, (0, 0))
    rounded_icon.putalpha(mask)

    # 保存结果
    rounded_icon.save(output_path, 'PNG', optimize=True)
    print(f"✓ 已添加圆角效果: {output_path}")
    return True

def create_all_rounded_icons():
    """为所有尺寸的图标添加圆角效果"""
    icons_dir = "/Users/ethan/Codes/longimagereader/icons"

    # 处理主图标
    bg_path = "/Users/ethan/Codes/longimagereader/bg.png"
    main_icon_path = os.path.join(icons_dir, "app.png")

    print("开始为图标添加macOS圆角效果...")

    if apply_rounded_corners_to_icon(bg_path, main_icon_path):
        print("✓ 主图标圆角处理完成")
    else:
        return False

    # 读取处理后的主图标
    main_icon = Image.open(main_icon_path)

    # 生成其他尺寸
    sizes = [16, 32, 48, 64, 128, 256, 512]

    for size in sizes:
        print(f"生成 {size}x{size} 圆角图标...")

        # 缩放主图标
        if size == main_icon.size[0]:
            resized_icon = main_icon
        else:
            # 先缩放到目标尺寸
            temp_icon = main_icon.resize((size, size), Image.Resampling.LANCZOS)

            # 重新应用圆角（因为缩放可能影响边缘）
            mask = create_squircle_mask(size)
            resized_icon = Image.new('RGBA', (size, size), (0, 0, 0, 0))
            resized_icon.paste(temp_icon, (0, 0))
            resized_icon.putalpha(mask)

        # 保存
        filename = f"app_{size}x{size}.png"
        output_path = os.path.join(icons_dir, filename)
        resized_icon.save(output_path, 'PNG', optimize=True)
        print(f"✓ 生成 {filename}")

    print("\n✅ 所有圆角图标生成完成！")
    return True

if __name__ == "__main__":
    create_all_rounded_icons()